package com.coolgor.coldot.common.database;

import com.coolgor.coldot.common.database.*;
import com.coolgor.coldot.exceptions.database.DatabaseOperationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.List;

@Component
public class DatabaseUtil {

    private static Logger log = LoggerFactory.getLogger(DatabaseUtil.class);

    //注意：查询操作完成后，因为还需提取结果集中信息，所以仍保持连接，在结果集使用完后才通过DBUtils.releaseSource()手动释放连接
    public static DataTable select(String sql) {
        Connection connection = C3p0Util.getConnection();
        Statement statement = null;
        ResultSet rs = null;
        DataTable dt = null;
        try{
            statement = connection.createStatement();
            rs = statement.executeQuery(sql);
            if (null!=rs) {
                dt = new DataTable();
                dt.Create(rs);
            }
        } catch (SQLException e){
            log.error("SQL语法有误: ",e);
            throw new DatabaseOperationException("!!DatabaseUtil execute error : "+e);
        } finally {
            C3p0Util.close(connection,statement,rs);
        }
        return dt ;
    }

    public static DataTable select(String sql, List<String> list) {
        Connection connection = C3p0Util.getConnection();
        PreparedStatement statement = null;
        ResultSet rs = null;
        DataTable dt = null;
        try{
            statement = connection.prepareStatement(sql);
            if (null!=list && list.size()>0){
                for (int i = 0; i < list.size(); i++) {
                    statement.setString(i+1, list.get(i));
                }
            }
            rs = statement.executeQuery();
            if (null!=rs) {
                dt = new DataTable();
                dt.Create(rs);
            }
        } catch (SQLException e){
            log.error("SQL语法有误: ",e);
            throw new DatabaseOperationException("!!DatabaseUtil execute error : "+e);
        } finally {
            C3p0Util.close(connection,statement,rs);
        }
        return dt ;
    }

    //而update操作完成后就可以直接释放连接了，所以在方法末尾直接调用了
    public static int update(String sql) {
        return update(sql, null);
    }

    public static int update(String sql, List<String> list) {
        int result = 0;
        Connection connection = C3p0Util.getConnection();
        PreparedStatement statement = null;
        try{
            statement = connection.prepareStatement(sql);
            if (null!=list && list.size()>0){
                for (int i = 0; i < list.size(); i++) {
                    statement.setString(i+1, list.get(i));
                }
            }
            result = statement.executeUpdate();
        } catch (SQLException e){
            log.error("SQL语法有误: ",e);
            throw new DatabaseOperationException("!!DatabaseUtil execute error : "+e);
        }
        C3p0Util.close(connection,statement,null);
        return result ;
    }
}
